//
//  HomeViewModelTests.swift
//  SwiftUI-DemoTests
//

import Testing
import Swinject
@testable import SwiftUI_Demo

struct HomeViewModelTests {
    // 测试专用容器配置
    private static let testContainer: Container = {
        let container = Container()
        
        // 注册Mock版本的Repository
        container.register(RepositoryProtocl.self) { _ in
            MockComponentsRepositoryImp(shouldSucceed: true)
        }
        
        // 注册UseCase绑定
        container.register(ComponentsUseCase.self) { resolver in
            ComponentsUseCaseImp()
        }
        
        return container
    }()
    
    @Test func testFetchComponentsSuccess() async {
        let viewModel = await HomeViewModel(
            componentsUseCase: Self.testContainer.resolve(ComponentsUseCase.self)!
        )
        
        // 验证
        await #expect(viewModel.components.count == 3)
        await #expect(viewModel.isLoading == false)
        
        // 验证组件内容
        if case .banner(let title) = await viewModel.components[0] {
            #expect(title == "测试横幅", "预期横幅标题不匹配")
        } else {
            #expect(Bool(false), "第一个组件应该是banner类型")
        }
        
        if case .quickEntry(let items) = await viewModel.components[1] {
            #expect(items.count == 2, "快速入口数量不匹配")
            #expect(items[0].title == "测试入口1", "第一个入口标题不匹配")
            #expect(items[1].title == "测试入口2", "第二个入口标题不匹配")
        } else {
            #expect(Bool(false), "第二个组件应该是quickEntry类型")
        }
        
        if case .promotion(let title) = await viewModel.components[2] {
            #expect(title == "测试促销", "促销标题不匹配")
        } else {
            #expect(Bool(false), "第三个组件应该是promotion类型")
        }
    }
    
    @Test func testFetchComponentsFailure() async {
        // 准备
        let mockUseCase = MockComponentsUseCase()
        mockUseCase.shouldSucceed = false
        
        let viewModel = await HomeViewModel(componentsUseCase: mockUseCase)
        
        // 执行
        await viewModel.fetchComponents()
        
        // 验证
        await #expect(viewModel.components.isEmpty)
        await #expect(viewModel.isLoading == false)
    }
    
    @Test func testLoadingState() async {
        // 准备
        let mockUseCase = MockComponentsUseCase()
        mockUseCase.fetchComponents = { [mockComponents = mockUseCase.mockComponents] in
            try await Task.sleep(nanoseconds: 500_000_000)
            return mockComponents
        }
        
        let viewModel = await HomeViewModel(componentsUseCase: mockUseCase)
        
        // 执行
        await viewModel.fetchComponents()
        
        // 验证加载状态为true
        await #expect(viewModel.isLoading == true)
        
        // 验证加载完成后状态为false
        await #expect(viewModel.isLoading == false)
        await #expect(viewModel.components.count == 3)
    }
}
